package repeat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-10-10
 * Time: 10:09
 */
public class UdpDatagramServer {
    //创建一个socket对象
    public DatagramSocket socket = null;//socket文件读写网卡
    public UdpDatagramServer(int port) throws SocketException {
        socket = new DatagramSocket(port);//手动分配服务器端口号
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //数据报包做数据的基本单位
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096] , 4096);//把传过来的数据放到数据报包中，内置数组存数据字节，被使用的长度
            //socket文件接收数据
            socket.receive(requestPacket);//从socket内存缓存区中读，无则阻塞
            //再用字符串接收一下
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());//转化为字符串，有效数据长度
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());//字符串转数组，获取数组长度,包含请求的ip和端口
            socket.send(responsePacket);

            System.out.printf("[%s,%d] request：%s  response：%s\n",requestPacket.getAddress().toString()
                    ,requestPacket.getPort(),request,response);//客户端ip地址，端口号,请求，响应
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpDatagramServer server = new UdpDatagramServer(9096);
        server.start();
    }
}
